import pymysql


class MyORM:
    def __init__(self):
        conn = pymysql.connect(
            host='127.0.0.1',
            port=3306,
            user='root',
            password='123456',
            database='mumushouji',
            charset='utf8',
            autocommit=True,
            cursorclass=pymysql.cursors.DictCursor
        )
        cursor = conn.cursor()
        self.cursor = cursor

    def execute(self, sql):
        self.cursor.execute(sql)
        return self.cursor.fetchall()


class User:
    table_name = 'user'

    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            self.__setattr__(k, v)

    def query_one(self, select_params=None, **where_params):
        if select_params is not None and type(select_params) is list:
            sql = 'select '
            for i in select_params:
                sql += i + ' ,'
            sql = sql[:-1]
        else:
            sql = 'select * '
        sql += 'from %s' % self.table_name
        print(where_params)
        if where_params is not None:
            sql += ' where '
            for k, v in where_params.items():
                sql += " %s = '%s' and" % (k, v)
            sql += ' 1=1 limit 1'

        print(sql)
        return MyORM().execute(sql)

    def insert(self):
        keys, values = [], []
        for k, v in self.__dict__.items():
            keys.append(k)
            values.append(v)
        sql = 'insert into %s(%s) values("%s")' % (self.table_name, ','.join(keys), '","'.join(values))
        print(sql)
        return MyORM().execute(sql)


if __name__ == '__main__':
    from icecream import ic

    user = User(username='dazhoulaoshi', password='123', nickname='大周老师', picture='1.jpg', job='全栈工程师')
    user.insert()
